package com.yootk.servlet.handler;

import com.yootk.dbc.DatabaseConnection;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.sql.PreparedStatement;
import java.util.List;

public class ImportHandler {
    private String filePath;

    public ImportHandler(String filePath) {
        this.filePath = filePath;
    }

    public void saveData() throws Exception {    // 数据存储
        PreparedStatement pstmt = null;
        try {
            DatabaseConnection.getConnection().setAutoCommit(false); // 取消自动提交
            String sql = "INSERT INTO logs(device, intime, status) VALUES (?,?,?)";
            pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
            SAXReader saxReader = new SAXReader();        // 默认的SAX解析器
            Document document = saxReader.read(new FileInputStream(new File(this.filePath))); // 读取文档
            Element rootElement = document.getRootElement();    // 读取根元素
            List<Element> infoList = rootElement.elements("info"); // 获取元素集合
            for (Element element : infoList) { // 元素迭代
                pstmt.setString(1, element.elementText("device"));
                pstmt.setTimestamp(2, new java.sql.Timestamp(Long.parseLong(element.elementText("intime"))));
                pstmt.setInt(3, Integer.parseInt(element.elementText("status")));
                pstmt.addBatch(); // 追加批处理
            }
            pstmt.executeBatch(); // 执行批处理
            DatabaseConnection.getConnection().commit(); // 事务提交
        } catch (Exception e) {
            DatabaseConnection.getConnection().rollback(); // 事务回滚
            throw e;
        } finally {
            DatabaseConnection.close(); // 数据库关闭
        }
    }
}
